package com.xiaobai.spike.service.client.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaobai.spike.entity.OauthClientDetails;
import com.xiaobai.spike.entity.User;
import com.xiaobai.spike.mapper.OauthClientDetailsMapper;
import com.xiaobai.spike.model.request.GetListByUserRequest;
import com.xiaobai.spike.model.request.OauthClientDetailAddRequest;
import com.xiaobai.spike.sdk.lang.BusinessRuntimeException;
import com.xiaobai.spike.sdk.lang.Errors;
import com.xiaobai.spike.service.auth.UserService;
import com.xiaobai.spike.service.client.OauthClientDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.UUID;

@Service
public class OauthClientDetailsServiceImpl implements OauthClientDetailsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OauthClientDetailsServiceImpl.class);

    @Resource
    private OauthClientDetailsMapper oauthClientDetailsMapper;

    @Resource
    private UserService userService;

    @Override
    public OauthClientDetails add(OauthClientDetailAddRequest oauthClientDetailAddRequest) {
        User user = userService.getById(oauthClientDetailAddRequest.getUserId());
        if (null == user) {
            throw new BusinessRuntimeException(Errors.USER_NOT_EXITS);
        }
        oauthClientDetailAddRequest.setCreateUser(user.getId());
        QueryWrapper<OauthClientDetails> userQueryWrapper = Wrappers.query();
        userQueryWrapper
                .orderByDesc("id").last("limit 1");
        OauthClientDetails oauthClientDetails = oauthClientDetailsMapper.selectOne(userQueryWrapper);
        String id = "10000";
        if (oauthClientDetails == null) {
            oauthClientDetailAddRequest.setId(id + autoGenericCode("0", 5));
        } else {
            oauthClientDetailAddRequest.setId(id + autoGenericCode(oauthClientDetails.getId().substring(5),5));
        }

        oauthClientDetailAddRequest.setSecret(UUID.randomUUID().toString());
        int insert = oauthClientDetailsMapper.insert(oauthClientDetailAddRequest);

        if (insert == 1) {
            return oauthClientDetailAddRequest;
        }
        throw new BusinessRuntimeException(-1, "新增失败");
    }

    /**
     * 不够位数的在前面补0，保留num的长度位数字
     * @param code
     * @return
     */
    private static String autoGenericCode(String code, int num) {
        String result = "";
//         保留num的位数
//         0 代表前面补充0
//         num 代表长度为4
//         d 代表参数为正数型
        result = String.format("%0" + num + "d", Integer.parseInt(code) + 1);

        return result;
    }


    @Override
    public Integer updateById(OauthClientDetails oauthClientDetails) {
        return oauthClientDetailsMapper.updateById(oauthClientDetails);
    }

    @Override
    public OauthClientDetails getById(String id) {
        return oauthClientDetailsMapper.selectById(id);
    }

    @Override
    public IPage<OauthClientDetails> getListByUser(GetListByUserRequest getListByUserRequest) {
        QueryWrapper<OauthClientDetails> userQueryWrapper = Wrappers.query();
        userQueryWrapper.eq("createUser", getListByUserRequest.getUserId())
                .orderByDesc("timeCreated");
        return oauthClientDetailsMapper.selectPage(new Page<>(getListByUserRequest.getPage(), getListByUserRequest.getRowsPerPage()), userQueryWrapper);
    }
}
